<?php
error_reporting( 1023 );
$dba	= parse_ini_file( "config/db_access.ini" );
$prefix	= $dba['prefix'];
mysql_connect( $dba['hostname'], $dba['username'], $dba['password'] );
mysql_select_db( $dba['database'] );

$cacheFile	= "dump.serial";

$change		= isset( $_REQUEST['change'] ) ? true : false;
$verbose	= isset( $_REQUEST['verbose'] ) ? true : false;
$commit		= isset( $_REQUEST['commit'] ) ? true : false;


function verbodeLine( $line )
{
	echo "<br/>".$line;
}

function queryMysql( $query, $verbose = false )
{
	if( $verbose )
		verbodeLine( $query );
	return mysql_query( $query );
}
if( file_exists( $cacheFile ) )
{
	$data	= unserialize( file_get_contents( $cacheFile ) );
}
else
{
	$data	= array();
	$query	= "SELECT * FROM ".$prefix."bugs";
	$result	= mysql_query( $query ) or die( mysql_error() );
	while( $entry = mysql_fetch_array( $result ) )
	{
		$data[]	= array(
			"bug_id"	=> $entry['bug_id'],
			"timestamp"	=> $entry['timestamp'],
			);
	}
	if( $cacheFile )
	{
		file_put_contents( $cacheFile, serialize( $data ) );
	}
}

if( $change )
{
	queryMysql( "START TRANSACTION", $verbose );
	$query	= "ALTER TABLE `".$prefix."bugs` CHANGE `timestamp` `created` VARCHAR( 12 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL";
	queryMysql( $query, $verbose );
	$query	= "ALTER TABLE `".$prefix."bugs` ADD `modified` VARCHAR( 12 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL AFTER `created`";
	queryMysql( $query, $verbose );

	foreach( $data as $entry )
	{
		$query	= "UPDATE ".$prefix."bugs SET created='".$entry['timestamp']."', modified='".$entry['timestamp']."' WHERE bug_id=".$entry['bug_id'];
		if( $verbose )
			verbodeLine( $query );
		queryMysql( $query, $verbose );	
	}
	queryMysql( ( $commit ? "COMMIT" : "ROLLBACK"), $verbose );
}
else
{
	die( "
<html>
<body>
  <h1>BugTracker Timestamp Update</h1>
  Syntax:
  <pre>
    ./dump.php5?change(&verbose(&commit))
  </pre>
</body>
</html>"
	);
}
?>